<template>
  <div>
    <el-dialog v-model="dialogVisible" title="添加IAA自动投放" @close="handleClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" :validateOnRuleChange="false">
        <div class="flex">
          <div class="left w-[50%] shrink-0">
            <el-form-item label="链接类型">
              <el-select v-model="curType" disabled>
                <el-option v-for="(item, key) in appTypeList" :key="key" :value="item.type" :label="item.desc"></el-option>
              </el-select>
              <div class="text-[12px] text-[#68affb] tips">目前仅支持端原生IAA</div>
            </el-form-item>
            <el-form-item label="商品名称" prop="trade_name">
              <el-input v-model="form.trade_name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item label="日预算" prop="budget">
              <el-input type="number" v-model="form.budget" :min="300" :max="9999999.99" placeholder="请输入日预算" />
              <div class="text-[12px] text-[#68affb] tips">预算不少于300元，不超过9999999.99元</div>
            </el-form-item>
            <el-form-item label="ROI系数" prop="roi_goal">
              <el-input type="number" v-model="form.roi_goal" :min="0.01" :max="5" placeholder="请输入ROI系数" />
              <div class="text-[12px] text-[#68affb] tips">不小于0.01，不超过5,支持最多四位小数</div>
            </el-form-item>
            <!-- <el-form-item label="投放时段" prop="times"> -->
            <!-- <TimeSelect ref="'timeSelectRef'" @get-value="(val) => getTimeValue(val)" /> -->
            <!-- </el-form-item> -->

            <el-form-item label="排序方式" prop="share_sort">
              <el-select v-model="form.share_sort" placeholder="请选择排序方式">
                <el-option v-for="(item, index) in sortordList" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="短剧名称">
              <el-input v-model="form.drama_name" placeholder="请输入短剧名称,默认为商品名称" />
            </el-form-item>
            <el-form-item label="收费集数">
              <el-input
                type="number"
                v-model="form.subscription_series"
                class="text-center"
                :min="1"
                placeholder=""
                :disabled="props.model === 'edit'"
              >
                <template #prefix>第</template>
                <template #suffix>集</template>
              </el-input>
            </el-form-item>
            <el-form-item label="解锁金币数量">
              <el-input type="number" v-model="form.price" placeholder="请输入解锁金币数量" :disabled="props.model === 'edit'" />
            </el-form-item>
            <el-form-item label="项目状态">
              <el-switch v-model="form.operation" inline-prompt active-text="开启" inactive-text="关闭" />
            </el-form-item>
          </div>
          <div class="right w-[50%] shrink-0">
            <!-- <el-form-item label="项目ID">
          <el-input v-model="form.project_id" placeholder="请输入项目ID" />
        </el-form-item> -->
            <el-form-item label="账户列表" ref="accountRef" :prop="!form.advertiser_num ? 'account' : ''">
              <el-input
                v-model="form.account"
                type="textarea"
                resize="none"
                :rows="3"
                placeholder="请输入账户ID，多个账户ID用英文逗号隔开"
                :disabled="props.model === 'edit' || form.advertiser_num > 0"
                @input="handleAccountChange"
              />
            </el-form-item>
            <el-form-item label="账户数量" ref="advertiserNumRef" :prop="!form.account ? 'advertiser_num' : ''">
              <el-input
                v-model="form.advertiser_num"
                type="number"
                :max="10"
                placeholder="请输入账户数量"
                :disabled="props.model === 'edit' || (form.account != '' && form.account != null)"
                @input="handleAdvertiserNumChange"
              />
            </el-form-item>
            <el-form-item label="项目ID列表" ref="projectRef" :prop="!form.project_num ? 'project' : ''">
              <el-input
                v-model="form.project"
                type="textarea"
                resize="none"
                :rows="3"
                placeholder="请输入项目ID，多个项目ID用英文逗号隔开"
                :disabled="form.project_num > 0"
                @input="handleProjectChange"
              />
            </el-form-item>
            <el-form-item label="项目数量" ref="projectNumRef" :prop="!form.project ? 'project_num' : ''">
              <el-input
                v-model="form.project_num"
                type="number"
                placeholder="请输入项目数量"
                :disabled="form.project != '' && form.project != null"
                @input="handleProjectNumChange"
              />
            </el-form-item>

            <el-form-item label="单个项目广告数量" prop="number">
              <el-input type="number" v-model="form.number" placeholder="请输入单个项目广告数量" />
            </el-form-item>
            <el-form-item label="视频数量">
              <el-input type="number" v-model="form.video_num" placeholder="请输入视频数量" />
            </el-form-item>
            <el-form-item label="广告绑定视频数量">
              <el-input type="number" v-model="form.bound_video_num" placeholder="请输入广告绑定视频数量" />
            </el-form-item>
            <el-form-item label="是否共享视频账户">
              <el-radio-group v-model="form.is_push">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" :loading="buttonLoading">取消</el-button>
          <el-button type="primary" @click="submit" :loading="buttonLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="resDialogVisible" title="投放结果" @close="handleResClose" width="1200">
      <div class="mb-[15px] flex items-center refresh" :class="queryType === 'user' ? 'justify-between' : 'text-end  justify-end'">
        <div class="">用户：{{ userStore.nickname }}</div>
        <el-button type="primary" @click="refresh" :loading="buttonLoading">刷新</el-button>
      </div>
      <el-table :data="addRes" :v-loading="buttonLoading">
        <el-table-column prop="advertiser_id" label="广告主ID" />
        <el-table-column prop="advertiser_name" label="广告主名称" />
        <el-table-column prop="trade_name" label="商品名" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="status" label="项目成功数量">
          <template #default="{ row }">
            {{ row.project_ok_num }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="项目失败数量">
          <template #default="{ row }">
            <el-tooltip effect="dark" placement="top">
              <template #content>
                <div v-if="row.project_fail?.num > 0">
                  <div v-html="row.project_fail?.msg"></div>
                </div>
                <div v-else>无</div>
              </template>
              <div class="flex flex-col cursor-pointer taglist">
                {{ row.project_fail.num }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="广告成功数量">
          <template #default="{ row }">
            {{ row.advertiser_ok_num }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="广告失败数量">
          <template #default="{ row }">
            <el-tooltip effect="dark" placement="top">
              <template #content>
                <div v-if="row.advertiser_fail?.num > 0">
                  <div v-html="row.advertiser_fail?.msg"></div>
                </div>
                <div v-else>无</div>
              </template>
              <div class="flex flex-col cursor-pointer taglist">
                {{ row.advertiser_fail.num }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="queryType === 'user'"
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="refresh"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { automaticPlacementIaa } from '@/api/ai';
import { IaaAutomaticPlacementVO } from '@/api/ai/types';
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  appTypeList: {
    type: Array
  },
  curRow: {
    type: Object
  },
  model: {
    type: String,
    default: 'add'
  }
});

const queryType = ref('user');

const total = ref(0);

const sortordList = [
  { value: 'create_time_desc', label: '创建日期由近到远' },
  { value: 'create_time_asc', label: '创建日期由远到近' },
  { value: 'stat_cost_desc', label: '消耗由高到低' },
  { value: 'stat_cost_asc', label: '消耗由低到高' },
  { value: 'ctr_desc', label: '点击率由高到低' },
  { value: 'ctr_asc', label: '点击率由低到高' },
  { value: 'conversion_cost_desc', label: '转化成本由高到低' },
  { value: 'conversion_cost_asc', label: '转化成本由低到高' },
  { value: 'conversion_rate_desc', label: '转换率由高到低' },
  { value: 'conversion_rate_asc', label: '转换率由低到高' },
  { value: 'duration_desc', label: '时长从长到短' },
  { value: 'duration_asc', label: '时长从短到长' }
];

const dialogVisible = ref(false);
const resDialogVisible = ref(false);
const emit = defineEmits(['update:visible', 'refresh']);
watch(
  () => props.show,
  (val) => {
    dialogVisible.value = val;
  },
  {
    immediate: true
  }
);
const userStore = useUserStore();

const qeuryRes = ref([]);

const addRes = ref([]);

const buttonLoading = ref(false);

const formRef = ref(null);

const account = ref('');

const project = ref('');

const advertiserNumRef = ref();

const projectNumRef = ref();

const projectRef = ref();

const accountRef = ref();

const curType = ref('7');

const form = reactive<IaaAutomaticPlacementVO>({
  // library_name: '端',
  user: userStore.nickname, //用户
  dept_id: String(userStore.deptId), //部门id
  trade_name: '', //行业名称
  budget: 1000, //预算
  roi_goal: 1.05, //ROI系数
  number: null, //数量
  is_push: false, //是否推送
  drama_name: null, //剧本名称
  account: '', //账号
  advertiser_ids: [], //广告主id
  advertiser_num: null, //广告主数量
  project_id: '', //项目id
  price: null, //价格
  operation: false, //是否开启
  external_url_material: null,
  source: null,
  share_sort: 'stat_cost_desc',
  project: '',
  project_num: null,
  project_ids: [],
  subscription_series: null,
  video_num: null,
  bound_video_num: 1
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  ids: [],
  user: userStore.nickname
});

watch(
  () => props.curRow,
  (val) => {
    nextTick(() => {
      form.account = props.curRow.thirdAdvertiserId;
      curType.value = props.curRow.referralLinkType.toString();
      form.trade_name = props.curRow.dramaTitle;
    });
  }
);
// watch(
//   () => form.advertiser_num,
//   () => {
//     if (form.advertiser_num) {
//       form.is_push = true;
//     } else {
//       form.is_push = false;
//     }
//   }
// );

const validateNumber = (rule: any, value: any, callback: any) => {
  const numValue = Number(value);

  // 检查是否为有效数字
  if (value && !/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error('请输入数字，最多保留两位小数'));
  } else if (numValue < 300 || numValue > 9999999.99) {
    callback(new Error('数字必须介于 300 和 9999999.99 之间'));
  } else {
    callback();
  }
};
const validateRoiNumber = (rule: any, value: any, callback: any) => {
  const numValue = Number(value);

  // 检查是否为有效数字
  if (value && !/^\d+(\.\d{1,4})?$/.test(value)) {
    callback(new Error('请输入数字，最多保留四位小数'));
  } else if (numValue < 0.01 || numValue > 5) {
    callback(new Error('数字必须介于 0.01 和 5 之间'));
  } else {
    callback();
  }
};
const validateAdvertiserNumber = (rule: any, value: any, callback: any) => {
  const numValue = Number(value);

  // 检查是否为有效整数
  if (value && !/^\d+$/.test(value)) {
    callback(new Error('请输入整数'));
  } else if (numValue < 0 || numValue > 10) {
    callback(new Error('数字必须介于 0 和 10 之间'));
  } else {
    callback();
  }
};

const rules = {
  trade_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  roi_goal: [
    { required: true, message: '请输入ROI系数', trigger: 'blur' },
    { validator: validateRoiNumber, trigger: 'blur' }
  ],
  share_sort: [{ required: true, message: '请选择排序方式', trigger: 'blur' }],
  // advertiser_ids: [{ required: true, message: '请填写广告主', trigger: 'blur' }],
  advertiser_num: [
    { required: true, message: '请填写广告主数量', trigger: 'blur' },
    { validator: validateAdvertiserNumber, trigger: 'blur' }
  ],
  // project_ids: [{ required: true, message: '请填写广告主', trigger: 'blur' }],
  project_num: [{ required: true, message: '请填写项目数量', trigger: 'blur' }],
  account: [{ required: true, message: '请填写广告主', trigger: 'blur' }],
  project: [{ required: true, message: '请填写项目列表', trigger: 'blur' }],
  price: [{ required: true, message: '请填写金币数量', trigger: 'blur' }]
};
// 初始化函数
const resetForm = () => {
  // form.library_name = '端';
  form.user = userStore.nickname;
  form.dept_id = String(userStore.deptId);
  form.trade_name = '';
  form.budget = 300;
  form.roi_goal = 0.01;
  form.number = null;
  form.account = null;
  form.is_push = false;
  form.drama_name = null;
  form.advertiser_ids = [];
  form.advertiser_num = null;
  form.project_id = null;
  form.price = null;
  form.operation = false;
  form.external_url_material = null;
  form.source = null;
  form.project = null;
  form.project_ids = [];
  form.project_num = null;
  form.subscription_series = null;
  form.share_sort = 'stat_cost_desc';
  form.video_num = null;
  form.bound_video_num = 1;
};
const handleAccountChange = () => {
  if (form.account) {
    advertiserNumRef.value?.clearValidate();
  }
};
const handleAdvertiserNumChange = () => {
  if (form.advertiser_num) {
    accountRef.value?.clearValidate();
  }
};
const handleProjectChange = () => {
  if (form.project) {
    projectNumRef.value?.clearValidate();
  }
};
const handleProjectNumChange = () => {
  if (form.project_num) {
    projectRef.value?.clearValidate();
  }
};
/**
 * 关闭弹窗
 */
const handleClose = () => {
  resetForm();
  emit('update:visible', false);
};
const handleResClose = () => {
  resDialogVisible.value = false;
};

const getScores = async (data) => {
  try {
    const response = await fetch(import.meta.env.VITE_BASE_AI_URL + 'automatic_placement/inner/automatic_placement_iaa', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    const result = await response.json(); // 解析 JSON 数据
    return result; // 返回结果
  } catch (err) {
    throw err; // 可选择抛出错误以供调用时处理
  }
};

const getTimeValue = (time) => {
  // console.log('time', time);
};

/**
 * 提交数据
 */
const submit = async () => {
  if (form.dept_id == '0' || form.dept_id == 'null') {
    proxy?.$modal.msgError('您没有部门信息，请联系管理员');
    return;
  }
  formRef.value?.validate(async (valid: boolean) => {
    queryType.value = 'create';
    if (valid) {
      //   if (!account.value && !form.advertiser_num) {
      //     proxy?.$modal.msgError('账户列表与账户数量二者必填其一');
      //     return;
      //   }

      buttonLoading.value = true;
      let accountList;
      if (form.account) {
        form.advertiser_ids = form.account.split(',').map((item) => Number(item));
        // accountList = account.value.split(',');
        // form.advertiser_ids = account.value;
        if (form.advertiser_ids.length > 10) {
          proxy?.$modal.msgError('账户数量不能超过10个');
          return;
        }
      }
      if (form.project) {
        form.project_ids = form.project.split(',').map((item) => Number(item));
      }
      form.budget = Number(form.budget);
      form.roi_goal = Number(form.roi_goal);
      form.number = Number(form.number);
      form.advertiser_num = Number(form.advertiser_num);
      form.price = Number(form.price);
      //后其会根据类型调用不同的接口
      proxy?.$modal.loading('');
      if (curType.value === '7') {
        try {
          const scores = await getScores(form);
          if (scores.code != 0) {
            proxy?.$modal.msgError(scores.message);
            return;
          }
          emit('update:visible', false);
          resDialogVisible.value = true;
          qeuryRes.value = scores.row_id;
          queryParams.ids = scores.row_id;
          const res = await getResultCreate();
          addRes.value = res.data;
          // const result = getResultMsg(scores.result);
          // // await automaticPlacementIaa(form);
          // if (result) {
          //   proxy?.$modal.msgSuccess('操作成功');
          // } else {
          //   proxy?.$modal.msgWarning('部分成功');
          // }

          emit('refresh');
        } catch (error) {
        } finally {
          buttonLoading.value = false;
          proxy?.$modal.closeLoading();
        }
      } else {
        buttonLoading.value = false;
        proxy?.$modal.msgError('非端原生IAA类型暂不支持');
        proxy?.$modal.closeLoading();
        emit('update:visible', false);
      }
    }
  });
};

const refresh = async () => {
  if (queryType.value === 'create') {
    try {
      buttonLoading.value = true;
      const res = await getResultCreate();
      addRes.value = res.data;
      total.value = res.count;
    } finally {
      buttonLoading.value = false;
    }
  } else {
    userQuery();
  }
};

const getResultCreate = async () => {
  try {
    const response = await fetch(import.meta.env.VITE_BASE_AI_URL + 'automatic_placement/inner/query_ids', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ ids: queryParams.ids, page: queryParams.pageNum, size: queryParams.pageSize })
    });

    const result = await response.json(); // 解析 JSON 数据
    return result; // 返回结果
  } catch (err) {
    throw err; // 可选择抛出错误以供调用时处理
  }
};

const getResultMsg = (result) => {
  let isOk = true;
  if (result) {
    result.map((item) => {
      item.project.map((subitem, subindex) => {
        if (!isOk) return;
        subitem.new_advertisement.map((titem, tindex) => {
          if (!isOk) return;
          if (item.code != 0) {
            isOk = false;
          }
        });
      });
    });
  }
  return isOk;
};

const resultBoxShow = () => {
  resDialogVisible.value = true;
  queryType.value = 'user';
};

const query = async () => {
  try {
    const response = await fetch(import.meta.env.VITE_BASE_AI_URL + 'automatic_placement/inner/query_ids', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ user: userStore.nickname, page: queryParams.pageNum, size: queryParams.pageSize })
    });

    const result = await response.json(); // 解析 JSON 数据
    return result; // 返回结果
  } catch (err) {
    throw err; // 可选择抛出错误以供调用时处理
  }
};
const userQuery = async () => {
  try {
    proxy?.$modal.loading('');
    buttonLoading.value = true;
    const res = await query();
    addRes.value = res.data;
    total.value = res.count;
  } finally {
    proxy?.$modal.closeLoading();
    buttonLoading.value = false;
  }
};

defineExpose({
  resultBoxShow,
  userQuery
});
</script>

<style lang="scss" scoped>
::v-deep(.text-center .el-input__inner) {
  text-align: center !important;
}
</style>
